/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-12-23 14:05:56
 * @LastEditors: cgt
 * @LastEditTime: 2021-12-28 18:40:27
 */
/**
 * 流动线
 * @igonre
 */
class FlowLineObject {
  constructor(width, height, map, option) {
    this.map = map;
    this.width = width;
    this.height = height;
    this.data = new Uint8Array(width * height * 4);

    this.option = Object.assign(
      {
        flowLength: 0.2,
        lineColor: '#ff0000',
        flowColor: '#ffffff'
      },
      option
    );

    this.getFlowImage();
  }

  onAdd() {
    let canvas = document.createElement('canvas');
    canvas.width = this.width;
    canvas.height = this.height;
    this.context = canvas.getContext('2d');
  }

  /**
   * 图像绘制方法
   * @desc 循环调用，绘制一帧动画，绘制完成后调用地图重绘方法，绘制下一帧，形成动画效果
   */
  render() {
    let duration = 1000;
    let t = performance.now() % duration / duration;

    let context = this.context;

    // 绘制线
    context.clearRect(0, 0, this.width, this.height);
    context.beginPath();
    let length = this.option.flowLength;
    context.fillStyle = this.option.lineColor;
    context.fillRect(0, 0, this.width, this.height);
    let x = this.width * t;
    if (t + length > 1) {
      context.drawImage(this.flowImage, x, 0, this.flowImage.width, this.height);
      context.drawImage(this.flowImage, x - this.width, 0, this.flowImage.width, this.height);
    } else {
      context.drawImage(this.flowImage, x, 0, this.flowImage.width, this.height);
    }

    // 更新图片数据
    this.data = context.getImageData(0, 0, this.width, this.height).data;

    // 调用地图重绘方法，加载下一帧动画
    this.map.triggerRepaint();

    // 返回true表示图片刷新完成
    return true;
  }

  /**
   * 生成流动线图片
   */
  getFlowImage() {
    let canvas = document.createElement('canvas');
    let length = this.option.flowLength;
    let width = this.width * length;
    canvas.width = width;
    canvas.height = this.height;
    let ctx = canvas.getContext('2d');
    let grd = ctx.createLinearGradient(0, 0, width, 0);
    grd.addColorStop(0, this.option.lineColor);
    grd.addColorStop(1, this.option.flowColor);
    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, this.width, this.height);
    this.flowImage = canvas;
  }
}

export default FlowLineObject;
